package infradev.commons.executedb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class Main {

	public static void main(String[] args) throws FileNotFoundException, IOException, InstantiationException,
												  IllegalAccessException, ClassNotFoundException, SQLException {
		Properties properties = new Properties();

		if (args.length == 0) {
			System.out.println("Inform configuration file.");
			System.exit(1);
		} else {
			properties.load(new FileReader(args[0]));
		}

		String username = properties.getProperty("username");
		String password = properties.getProperty("password");
		String connectionstring = properties.getProperty("connectionstring");
		String classname = properties.getProperty("classname");
		String driverfile = properties.getProperty("driverfile");
		String scriptfile = properties.getProperty("scriptfile");

		URL driverUrl = new URL(String.format("jar:%s!/", new File(driverfile).toURI()));
		URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { driverUrl });
		Driver driver = (Driver) Class.forName(classname, true, urlClassLoader).newInstance();
		DriverManager.registerDriver(new DriverShim(driver));

		Connection connection = DriverManager.getConnection(connectionstring, username, password);
		Statement statement = connection.createStatement();

		BufferedReader reader = new BufferedReader(new FileReader(scriptfile));

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
				statement.execute(line);
			}
		} catch (SQLException e) {
			throw new SQLException(line, e);
		} finally {
			statement.close();
			connection.close();
		}

		reader.close();

		System.out.println("Done...");
	}

}
